const app = getApp();
var config = require('../../config.js');
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    openId : '', //openId
    appId : '', //appId
    loginName : '', // 账号
    password : '',  // 密码
    orderId : '', //订单ID
    clientUserCode : '', //用户唯一编码
    paySources : '22', // 支付方式
    money : 0, //金额
    type : '', //支付类型 0 正常支付 1 二次支付
    onLinePayResult : '', //支付结果串
    payResult : '', //支付结果
    closeOriginalConsumeDetail : true,//如果支付状态 支付中， 切换了支付方式，是否关掉原来的交易记录(如果不关，不能继续支付)
    payParam : '', //支付结果参数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      openId : wx.getStorageSync('openid'),
      appId : config.appid,
      loginName : options.loginName,
      password : options.password,
      orderId : options.orderId,
      clientUserCode : options.clientUserCode,
      money : options.money,
      type : options.type,
      onLinePayResult : options.onLinePayResult
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    if(that.data.openId === '' || that.data.openId === null){
      that.getLogin();
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  toPay: function () {
    var that = this;
    that.generateOrder();
  },

  //获取微信openid
  getLogin(){
    var _this = this;
    //微信登录
    wx.login({
      success: res => {
        if (res.code) {
          _this.getOpenId(res.code);
        }
      }
    })
  },

  getOpenId: function (code) {
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    wx.hideTabBar();
    var _this = this
    wx.request({
      url: config.openIdUrl,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        "code": code,
        "tenantCode": "",
        "latitude": "",
        "longitude": ""
      },
      success: function (result) {
        var data = result.data;
        console.info(data);
        if (data.success) {
          if (data.openid) {
            _this.setData({
              openId : data.openid
            })
            wx.hideLoading();
          }
        } else {
          _this.tip(data.msg, 'none')
        }
      },
      fail: function ({ errMsg }) {
        console.log(errMsg)
      },
      complete: function () {
        wx.hideLoading();
      }
    })
    
  },

  /**生成商户订单 */
  generateOrder: function () {
    var that = this;
    wx.showLoading({
      title: '请求支付中...',
    })
    if(that.data.payParam !== ''){
      that.pay(that.data.payParam);
    }else{
      var param = {};
      param.orderId = that.data.orderId;
      param.clientUserCode = that.data.clientUserCode;
      param.paySources = that.data.paySources;
      param.openId = that.data.openId;
      param.appId = that.data.appId;
      param.closeOriginalConsumeDetail = that.data.closeOriginalConsumeDetail;
      console.log(JSON.stringify(param));
      //统一支付 
      return new Promise((resolve, reject) => {
        wx.request({
          url: config.mallHost + "pay/payOrder",
          method: 'POST',
          data: {
            userName : that.data.loginName,
            password : that.data.password,
            param : JSON.stringify(param)
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success: res => {
            resolve(res)
            console.log("++++:" + res)
            if(res.data.success){
              var payResult = JSON.parse(res.data.object.onLinePayResult)
              var pay = JSON.parse(payResult.responseBody);
              //发起支付 
              var timeStamp = pay.timeStamp;
              var packages = pay.package;
              var paySign = pay.paySign;
              var nonceStr = pay.nonceStr;
              var signType =  pay.signType;
              var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": signType, "nonceStr": nonceStr };
              that.setData({
                payParam : param
              })
              wx.hideLoading();
              that.pay(param);
            }else{
              wx.hideLoading();
              wx.showToast({
                title: res.data.message,
                icon : 'none'
              })
            }  
          },
          fail: res => {
            reject(res)
          }
        })
      })  
    }
  },

  /**
   * 二次支付
   */
  payAgain(){
    var that = this;
    var result = JSON.parse(that.data.onLinePayResult);
    console.log(result.responseBody);
    var onLinePayResult = JSON.parse(result.responseBody);
    var timeStamp = onLinePayResult.timeStamp;
    var packages = onLinePayResult.package;
    var paySign = onLinePayResult.paySign;
    var nonceStr = onLinePayResult.nonceStr;
    var signType =  onLinePayResult.signType;
    var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": signType, "nonceStr": nonceStr };
    that.pay(param);
  },

  pay(param){
    var that = this;``
    console.log('发起支付');
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: param.signType,
      paySign: param.paySign,
      success: function (event) {
        // success
        console.log(event);
        that.setData({
          payResult : 'success'
        })
        setTimeout(function(){
          wx.reLaunch({
            url: './wechatPayorderSuc?money=' + that.data.money + '&payResult=' + that.data.payResult,
          })
        },200)
      },
      fail: function (error) {
        // fail
        that.setData({
          payResult : 'fail'
        })
        wx.showToast({
          title: '支付失败，请联系管理员',
          icon : 'none'
        })
        console.log("支付失败，失败原因：" + error)
      },
      complete: function () {
        // complete
        console.log("pay complete")
      }
    });
  },

})